<template>
  <div ref="editorContainer" class="editor"></div>
</template>

<script>
import * as monaco from 'monaco-editor';
export default {
  name: 'MonacoEditor',
  props: {
    language: {
      type: String,
      default: 'json'
    },
    code: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      editor: null
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      console.log('初始化编辑器:'+this.language)
      // 初始化编辑器
      this.editor = monaco.editor.create(this.$refs.editorContainer, {
        value: this.code,
        theme: 'vs-dark',
        language: this.language,
        tabSize: 4,
        scrollBeyondLastLine: false,
        automaticLayout: true, // 自动布局
        readOnly: false,
        selectOnLineNumbers: true,//显示行号
        roundedSelection: false,
        cursorStyle: 'line',        //光标样式
        glyphMargin: true,  //字形边缘
        useTabStops: false,
        fontSize: 18,       //字体大小
        autoIndent:true,//自动布局
        quickSuggestionsDelay: 500,   //代码提示延时
      })

      // 设置初始化值
      if (this.code){
        this.editor.setValue(this.code)
      }

      // 监听内容变化
      this.editor.onDidChangeModelContent((event) => {
        // console.log(event,'event')
      })

      // 监听失去焦点事件
      this.editor.onDidBlurEditorText((e) => {
        // console.log(e)
      });
    },
    // 获取编辑框内容
    getValue() {
      return this.editor.getValue()
    },
    setValue(value){
      this.editor.setValue(value)
    },
    // 自动格式化代码
    format() {
      this.editor.trigger('anything', 'editor.action.formatDocument')
      // 或者
      // this.editor.getAction(['editor.action.formatDocument']).run()
    },
    changeEditor() {
      console.log('修改编辑器:'+this.language)
      if (this.editor === null) {
        this.init()
      }

      const oldModel = this.editor.getModel()
      const newModel = monaco.editor.createModel(
        this.code,
        this.language
      )

      if (oldModel) {
        oldModel.dispose()
      }
      this.editor.setModel(newModel)
    }
  },
  watch: {
    code:{
      handler(newVal,oldVal){
        this.editor.setValue(newVal)
      }
    },
    language: {
      handler(newVal,oldVal){
        this.changeEditor()
      }
    }
  }
}
</script>

<style scoped>
.editor {
  width: 100%;
  min-height: 400px;

  resize: vertical;
  overflow: auto;
}
</style>
